import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../../../models/order_model.dart';
import 'logic.dart';

class OrderListPage extends StatelessWidget {
  final OrderListLogic logic = Get.put(OrderListLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF8F9FA),
      appBar: _buildAppBar(),
      body: _buildBody(context),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Text(
        '我的订单',
        style: TextStyle(
          fontWeight: FontWeight.w600,
          fontSize: 18,
          color: Colors.white,
        ),
      ),
      backgroundColor: logic.primaryColor,
      elevation: 0,
      centerTitle: true,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(
          bottom: Radius.circular(16),
        ),
      ),
    );
  }

  Widget _buildBody(BuildContext context) {
    return Obx(() {
      return RefreshIndicator(
        color: logic.primaryColor,
        onRefresh: logic.loadOrders,
        child: _buildOrderList(context),
      );
    });
  }

  Widget _buildOrderList(BuildContext context) {
    if (logic.isLoading.value && logic.orders.isEmpty) {
      return _buildLoadingState();
    }

    if (logic.orders.isEmpty) {
      return _buildEmptyState(context);
    }

    return ListView.builder(
      padding: EdgeInsets.fromLTRB(16, 16, 16, 24),
      itemCount: logic.orders.length,
      itemBuilder: (context, index) {
        return AnimatedOrderCard(
          order: logic.orders[index],
          logic: logic,
          index: index,
        );
      },
    );
  }

  Widget _buildLoadingState() {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 50,
            height: 50,
            child: CircularProgressIndicator(
              color: logic.primaryColor,
              strokeWidth: 3,
            ),
          ),
          SizedBox(height: 16),
          Text(
            '加载订单中...',
            style: TextStyle(
              color: Colors.grey[600],
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState(BuildContext context) {
    return ListView(
      physics: AlwaysScrollableScrollPhysics(),
      children: [
        SizedBox(height: MediaQuery.of(context).size.height / 4),
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              padding: EdgeInsets.all(20),
              decoration: BoxDecoration(
                color: logic.primaryColor.withOpacity(0.1),
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.receipt_long_rounded,
                size: 70,
                color: logic.primaryColor.withOpacity(0.7),
              ),
            ),
            SizedBox(height: 24),
            Text(
              '暂无订单',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w600,
                color: Colors.grey[800],
              ),
            ),
            SizedBox(height: 8),
            Text(
              '您的订单将显示在这里',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey[600],
              ),
            ),
          ],
        ),
      ],
    );
  }
}

class AnimatedOrderCard extends StatelessWidget {
  final Order order;
  final OrderListLogic logic;
  final int index;

  const AnimatedOrderCard({
    Key? key,
    required this.order,
    required this.logic,
    required this.index,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      tween: Tween<double>(begin: 0.0, end: 1.0),
      duration: Duration(milliseconds: 300 + (index * 50)),
      builder: (context, value, child) {
        return Transform.translate(
          offset: Offset(0, 20 * (1 - value)),
          child: Opacity(
            opacity: value,
            child: child,
          ),
        );
      },
      child: OrderCard(order: order, logic: logic),
    );
  }
}

class OrderCard extends StatelessWidget {
  final Order order;
  final OrderListLogic logic;

  const OrderCard({
    Key? key,
    required this.order,
    required this.logic,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final dateFormat = DateFormat('yyyy-MM-dd HH:mm');

    return Obx(() {
      final isExpanded = logic.expandedOrderId.value == order.id;

      return Container(
        margin: EdgeInsets.only(bottom: 16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          children: [
            _buildCardHeader(dateFormat),
            _buildMainContent(isExpanded),
            AnimatedSize(
              duration: Duration(milliseconds: 200),
              child: Container(
                height: isExpanded ? null : 0,
                clipBehavior: Clip.antiAlias,
                decoration: BoxDecoration(),
                child: isExpanded
                    ? _buildOrderDetails()
                    : SizedBox.shrink(),
              ),
            ),
            _buildCardFooter(),
          ],
        ),
      );
    });
  }

  Widget _buildCardHeader(DateFormat dateFormat) {
    return Container(
      padding: EdgeInsets.fromLTRB(16, 16, 16, 8),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Icon(
                Icons.receipt_outlined,
                size: 18,
                color: logic.primaryColor,
              ),
              SizedBox(width: 6),
              Text(
                '订单号: ${order.id}',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ],
          ),
          _buildStatusTag(),
        ],
      ),
    );
  }

  Widget _buildStatusTag() {
    final statusColor = logic.getStatusColor(order.status);
    final statusText = logic.getStatusText(order.status);
    final statusIcon = logic.getStatusIcon(order.status);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 5),
      decoration: BoxDecoration(
        color: statusColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: statusColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            statusIcon,
            size: 14,
            color: statusColor,
          ),
          SizedBox(width: 4),
          Text(
            statusText,
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w500,
              color: statusColor,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMainContent(bool isExpanded) {
    final dateFormat = DateFormat('yyyy-MM-dd HH:mm');

    return Container(
      padding: EdgeInsets.fromLTRB(16, 8, 16, 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                Icons.access_time_rounded,
                size: 14,
                color: Colors.grey[500],
              ),
              SizedBox(width: 4),
              Text(
                dateFormat.format(order.createdAt),
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 12,
                ),
              ),
            ],
          ),

          Obx(() {
            if (logic.userType.value == 'MERCHANT' || logic.userType.value == 'ADMIN') {
              return Padding(
                padding: EdgeInsets.only(top: 8),
                child: Row(
                  children: [
                    Icon(
                      Icons.person,
                      size: 14,
                      color: Colors.grey[500],
                    ),
                    SizedBox(width: 4),
                    Text(
                      '用户: ${order.username}',
                      style: TextStyle(
                        color: Colors.grey[600],
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              );
            }
            return SizedBox.shrink();
          }),

          Divider(height: 24),

          _buildAddressSection(),

          if (order.remark.isNotEmpty) ...[
            SizedBox(height: 12),
            _buildRemarkSection(),
          ],

          SizedBox(height: 16),

          _buildTotalSection(isExpanded),
        ],
      ),
    );
  }

  Widget _buildAddressSection() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: logic.primaryColor.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(
            Icons.location_on_rounded,
            size: 16,
            color: logic.primaryColor,
          ),
        ),
        SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '收货地址',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[800],
                ),
              ),
              SizedBox(height: 4),
              Text(
                '${order.address} ${order.addressDetail}',
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildRemarkSection() {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          padding: EdgeInsets.all(8),
          decoration: BoxDecoration(
            color: logic.primaryColor.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(
            Icons.note_rounded,
            size: 16,
            color: logic.primaryColor,
          ),
        ),
        SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '备注',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[800],
                ),
              ),
              SizedBox(height: 4),
              Text(
                order.remark,
                style: TextStyle(
                  fontSize: 13,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildTotalSection(bool isExpanded) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Row(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
              decoration: BoxDecoration(
                color: logic.primaryColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Text(
                '${order.items.fold(0, (sum, item) => sum + item.quantity)}件商品',
                style: TextStyle(
                  color: logic.primaryColor,
                  fontWeight: FontWeight.w500,
                  fontSize: 12,
                ),
              ),
            ),
            TextButton(
              onPressed: () => logic.toggleOrderExpanded(order.id),
              style: TextButton.styleFrom(
                minimumSize: Size(60, 30),
                padding: EdgeInsets.symmetric(horizontal: 8),
              ),
              child: Row(
                children: [
                  Text(
                    isExpanded ? '收起' : '查看详情',
                    style: TextStyle(
                      color: logic.primaryColor,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  Icon(
                    isExpanded
                        ? Icons.keyboard_arrow_up
                        : Icons.keyboard_arrow_down,
                    size: 16,
                    color: logic.primaryColor,
                  ),
                ],
              ),
            ),
          ],
        ),
        Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              '¥${order.totalPrice.toStringAsFixed(2)}',
              style: TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 18,
                color: Colors.grey[800],
              ),
            ),
            Text(
              '(含配送费¥5.00)',
              style: TextStyle(
                fontSize: 11,
                color: Colors.grey[500],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildOrderDetails() {
    return Column(
      children: [
        Divider(height: 1, thickness: 1, color: Colors.grey[100]),
        Container(
          width: double.infinity,
          padding: EdgeInsets.all(16),
          color: Color(0xFFF9F9F9),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Container(
                    width: 4,
                    height: 14,
                    decoration: BoxDecoration(
                      color: logic.primaryColor,
                      borderRadius: BorderRadius.circular(2),
                    ),
                  ),
                  SizedBox(width: 6),
                  Text(
                    '订单详情',
                    style: TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 14,
                      color: Colors.grey[800],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),
              ...order.items.map((item) => _buildOrderItemRow(item)).toList(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildOrderItemRow(OrderItem item) {
    return Container(
      margin: EdgeInsets.only(bottom: 16),
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.03),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 60,
            height: 60,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 2,
                  offset: Offset(0, 1),
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: Image.network(
                item.foodImage,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[200],
                    child: Icon(Icons.image_not_supported, color: Colors.grey),
                  );
                },
              ),
            ),
          ),
          SizedBox(width: 12),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.foodName,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: Colors.grey[800],
                  ),
                ),
                SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '¥${item.price.toStringAsFixed(2)}',
                      style: TextStyle(
                        color: logic.primaryColor,
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                    ),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                      decoration: BoxDecoration(
                        color: Colors.grey[100],
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        'x${item.quantity}',
                        style: TextStyle(
                          color: Colors.grey[700],
                          fontSize: 12,
                          fontWeight: FontWeight.w500,
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCardFooter() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(16),
          bottomRight: Radius.circular(16),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: _buildOrderActions(),
      ),
    );
  }

  List<Widget> _buildOrderActions() {
    final List<Widget> actions = [];

    if (logic.userType.value == 'MERCHANT' || logic.userType.value == 'ADMIN') {
      switch (order.status) {
        case 'PAID':
          actions.add(_buildActionButton(
            '开始准备',
            Colors.blue,
                () => logic.updateOrderStatus(order.id, 'PREPARING'),
            Icons.restaurant_rounded,
          ));
          break;
        case 'PREPARING':
          actions.add(_buildActionButton(
            '开始配送',
            Colors.teal,
                () => logic.updateOrderStatus(order.id, 'DELIVERING'),
            Icons.delivery_dining_rounded,
          ));
          break;
        case 'DELIVERING':
          actions.add(_buildActionButton(
            '完成订单',
            Colors.green,
                () => logic.updateOrderStatus(order.id, 'COMPLETED'),
            Icons.check_circle_rounded,
          ));
          break;
      }
    } else {
      if (order.status == 'PENDING' || order.status == 'PAID') {
        actions.add(_buildActionButton(
          '取消订单',
          Colors.red,
              () => logic.cancelOrder(order.id),
          Icons.close_rounded,
          outlined: true,
        ));
      }

      if (order.status == 'COMPLETED') {
        actions.add(_buildActionButton(
          '再来一单',
          logic.primaryColor,
              () => logic.reorder(order),
          Icons.refresh_rounded,
        ));
      }
    }

    return actions;
  }

  Widget _buildActionButton(
      String text,
      Color color,
      VoidCallback onTap, IconData refresh_rounded, {
        IconData? icon,
        bool outlined = false,
      }) {
    return Padding(
      padding: EdgeInsets.only(left: 8),
      child: outlined
          ? OutlinedButton.icon(
        onPressed: onTap,
        icon: Icon(icon, size: 16),
        label: Text(text),
        style: OutlinedButton.styleFrom(
          foregroundColor: color,
          side: BorderSide(color: color),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        ),
      )
          : ElevatedButton.icon(
        onPressed: onTap,
        icon: Icon(icon, size: 16),
        label: Text(text),
        style: ElevatedButton.styleFrom(
          backgroundColor: color,
          foregroundColor: Colors.white,
          elevation: 0,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        ),
      ),
    );
  }
}